package ink.waita.blog.api.web.config

import com.alibaba.fastjson.JSON
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * create by aries
 * 全局异常处理器
 */

@ControllerAdvice
class GlobalErrorConfig {

    @ExceptionHandler
    void exceptionHappens(Exception e, HttpServletRequest request, HttpServletResponse response) {
        String json = null
        try {
            json = JSON.toJSONString(new ErrorResponse(500, new String("请稍候再试".getBytes(), "UTF-8")))
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace()
        }
        PrintWriter writer = null
        try {
            e.printStackTrace()
            writer = response.getWriter()
            writer.write(json)
            writer.flush()
        } catch (IOException e1) {
            e1.printStackTrace()
        } finally {
            if (writer != null)
                writer.close()
        }
    }
}

class ErrorResponse {
    def code
    def msg

    ErrorResponse(int code, String msg) {
        this.code = code
        this.msg = msg
    }
}
